<template>
  <NModal v-model:show="visible" title="授权资源" :mask-closable="false" transform-origin="center" preset="card" @after-leave="closeDrawer" class="w-1000px">
    <NScrollbar class="h-600px pr-20px">
      <NDataTable :columns="columns" :data="tableData" :single-line="false" striped />
    </NScrollbar>
    <template #footer>
      <NSpace justify="end" :size="16">
        <NButton @click="closeDrawer">取消</NButton>
        <NButton type="primary" @click="handleSubmit">提交</NButton>
      </NSpace>
    </template>
  </NModal>
</template>

<script setup lang="tsx">
import {reactive, toRefs, watch} from "vue";
import { NCheckbox } from 'naive-ui';
import {grantResource} from '@/service/api/resource-api'

defineOptions({
  name: 'GrantResourceModal'
});

interface Props {
  // 授权资源的角色ID
  rowData?: number;
}
interface Emits {
  (e: 'submitted'): void;
}

const emit = defineEmits<Emits>();

const props = defineProps<Props>();

const visible = defineModel<boolean>('resourceVisible', {
  default: false
});

const state = reactive({
  tableData: [] as Api.SystemManage.GrantResource[],
})
// 转为ref后解构
const {tableData} = {...toRefs(state)};

// 监听打开窗口时，逻辑处理
watch(visible, () => {
  if (visible.value) {
    console.log("授权资源")
    getGrantResource()
  }
})
// 授权资源查询
async function getGrantResource(){
 const {data} = await grantResource();
  console.log("data:",data)
  if(data != null){
    state.tableData=[...state.tableData, ...data]
  }
}

// 提交
async function handleSubmit() {
  getSelectedIds()
  // request
  window.$message?.success('操作成功');
  // 取消、关闭弹框
  closeDrawer();
  // 调用父组件事件
  emit('submitted');
}

// 取消、关闭弹框
function closeDrawer() {
  visible.value = false;
}

const columns = [
  {
    key: 'parentName',
    title: '一级目录',
    align: 'center',
    width: 100,
    titleColSpan:1,
    rowSpan: (rowData:Api.SystemManage.GrantResource, rowIndex:number) => {
      return getLastIndex( rowIndex, [rowData.parentId]);
    },
    render: (row:Api.SystemManage.GrantResource)=> (
      <NCheckbox v-model:checked={row.selected} onUpdate:checked={(checkedValue) => checkedParent(checkedValue,row) }>
        {row.parentName}
      </NCheckbox>
    )
  },
  {
    key: 'title',
    title: '菜单',
    align: 'center',
    width: 100,
    render: (row:Api.SystemManage.GrantResource)=> (
      <NCheckbox v-model:checked={row.selected} onUpdate:checked={(key) => checkedSub(key,row) }>
        {row.title}
      </NCheckbox>
    )
  },
  {
    key: 'button',
    title: '按钮',
    align: 'center',
    width: 100,
    render: (row:Api.SystemManage.GrantResource) => (
      <div>
        {
          row.button !=null ? row.button.length > 0 &&
            row.button.map(item => (
              <NCheckbox v-model:checked={item.selected} onUpdate:checked={(key) => checkedButton(key,item) }>
                {item.title}
              </NCheckbox>
            )) : null
        }
      </div>
    ),
  }
]
// 定义一个函数，用于获取相同名称的最后一行的索引
const getLastIndex = (index: number, names: number[]) => {
  const sameNameIndex = tableData.value.slice(index).findIndex((item) => {
    return names.some((name) => item["parentId"] !== name);
  });
  return sameNameIndex === -1 ? tableData.value.length  : sameNameIndex;
};

// 选中一级目录
function checkedParent(checkedValue: boolean,parentRow:Api.SystemManage.GrantResource){
  const parentId = parentRow.parentId;
  tableData.value.forEach(row => {
    if (row.parentId === parentId) {
      row.selected = checkedValue;
      row.button?.forEach(button => {
        checkedButton(checkedValue,button)
      });

    }
  });
}
// 选中菜单
function checkedSub(checkedValue: boolean,row:Api.SystemManage.GrantResource){
  const parentId = row.parentId;
  row.button?.forEach(button => {
    button.selected = checkedValue;
  });
  tableData.value.forEach(row => {
    if (row.parentId === parentId && row.title!== row.title) {
      row.selected = checkedValue;
    }
  });
}
// 选中按钮
function checkedButton(checkedValue: boolean,row:Api.SystemManage.GrantResourceButton){
  row.selected = checkedValue;
}
// 选中的数据集合
function getSelectedIds() {
  const selectedIds: number[] = [];
  tableData.value.forEach(row => {
    if (row.selected) {
      selectedIds.push(row.id);
      row.button?.forEach(button => {
        if (button.selected) {
          selectedIds.push(button.id);
        }
      });
    }
  });
  console.log('选中的数据 ID:', selectedIds);
}
</script>

<style scoped>

</style>
